<template>
  <section>
    <div class="shade-container">
      <el-row type="flex" justify="space-between" class="button-box">
        <el-col :span="6" class="left">
          设备影子
        </el-col>
        <el-col :span="18" class="right">
          <el-button type="primary" @click="refresh">刷新</el-button>
          <el-button type="primary" @click="updateShade">更新影子</el-button>
        </el-col>
      </el-row>
      <el-row class="textarea-box">
        <el-col :span="24">
          <el-input type="textarea" rows="20" readonly="true" :value="info.shadow ? JSON.stringify(JSON.parse(info.shadow), undefined, 2) : '' ">
          </el-input>
        </el-col>
      </el-row>
      <shade-template :title="'更新影子设备'" :dialogVisible.sync="dialogVisible" @submitForm="submitForm"  :info="info"></shade-template>
    </div>
  </section>
</template>

<script>
  import ShadeTemplate from '@views/device/components/ShadeTemplate'
  import { getDeviceShadow, updateDeviceShadow } from '@api/device'
  import { Vue, Component, Watch } from 'vue-property-decorator'

  @Component({
    components: {
      ShadeTemplate
    }
  })
  export default class DeviceShade extends Vue {
    data() {
      return {
        dialogVisible: false, //form表单是否显示
        id: -1, //设备id
        info: {} //影子信息
      }
    }
    mounted() {
      this.id = this.$route.params.id;
      this.fetchData(this.id);
    }
    fetchData(id) { //请求影子数据
      getDeviceShadow(id).then(response => {
        let res = response.data;
        if (res.status) {
          this.info = res.data;
        } else {
          this.showMessage(res.message, 'error');
        }
      })
    }
    showMessage(message, type, duration) { //提示信息共用方法
      this.$message({
        message: message,
        type: type || 'success', //success warning error
        duration: duration || 3 * 1000
      })
    }
    refresh() { //刷新
      this.fetchData(this.id);
    }
    updateShade() { //更新影子表单
      this.dialogVisible = true
    }
    submitForm(form) { //提交方法
      if (Object.keys(form.reported).length && Object.keys(form.desired).length) {
        form.id = this.id;
        updateDeviceShadow(form).then(response => {
          let res = response.data;
          if (res.status) {
            this.showMessage('更改设备影子成功', 'success');
            this.refresh();
            this.dialogVisible = false;
          } else {
            this.showMessage(res.message, 'error');
          }
        })
      } else {
        this.showMessage('请输入JSON格式', 'error');
      }
    }
  }
</script>

<style lang="scss" scoped>
  .shade-container {
    background-color: white;
    margin: 20px;

    .button-box {
      line-height: 60px;

      .left {
        font-size: 20px;
        font-weight: bold;
      }
    }

    .time-box {
      line-height: 30px;
      text-align: left;
      padding-left: 20px;
    }

    .textarea-box {
      width: 50%;
      line-height: 60px;
      padding: 10px 0 20px 20px;
    }
  }
</style>
